#include "framegeneratorimpl.h"

#include <QFileInfoList>
#include <QDir>
#include <KPluginFactory>
#include <KPluginLoader>
#include <KPluginInfo>
#include <QApplication>

#include <interfaces/kdcapplicationinterface.h>
extern KDCApplicationInterface *gKDCApplicationInterface;

FrameGeneratorImpl::FrameGeneratorImpl()
{

}

FrameGeneratorImpl::~FrameGeneratorImpl()
{

}

QList<KPluginInfo> FrameGeneratorImpl::pluginList() const
{
	QList<KPluginInfo> res;
	foreach( FramePluginInterface *interface, pPlugins )
		res.append( interface->info() );
	return res;
}

QPixmap FrameGeneratorImpl::preview( const QString &aName ) const
{
	foreach( FramePluginInterface *interface, pPlugins )
		if ( interface->info().name() == aName )
			return interface->preview();
	return QPixmap();
}

QPixmap FrameGeneratorImpl::createFrame( const QString &aName, QPixmap &aPix, int aWidth, int aHeight, QString &aError ) const
{
	foreach( FramePluginInterface *interface, pPlugins )
		if ( interface->info().name() == aName )
			return interface->create( aPix, aWidth, aHeight, aError );
	return QPixmap();
}

QAbstractListModel* FrameGeneratorImpl::createModel() const
{
	return 0;
}

bool FrameGeneratorImpl::init()
{ 
	if ( !gKDCApplicationInterface )
		return false;
	QDir path( gKDCApplicationInterface->applicationDirPath() + "/plugins/frames/" );
	QFileInfoList dirList = path.entryInfoList( QDir::Files );
	QList<QFileInfo>::const_iterator it;
	KPluginFactory *factory;
	FramePluginInterface *plugin;
	QList<FramePluginInterface*> plugins;
	for ( it = dirList.constBegin(); it != dirList.constEnd(); ++it )
	{
		factory = KPluginLoader( (*it).absoluteFilePath() ).factory();
		if ( factory )
		{
			plugin = factory->create<FramePluginInterface>();
			if ( plugin )
			{
				pPlugins.append( plugin );
				plugin->setApplicationInterface( gKDCApplicationInterface );
			}
		}
	}
	return true;
}
